package cn.tt.tuantuanerp.tuantuanerp.orderwebapi.service.impl;


import cn.tt.tuantuanerp.passport.service.IUserService;
import cn.tt.tuantuanerp.tuantuanerp.comment.ex.ServiceException;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.OrderAddNewDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.dto.SkuInOrderAddNewDTO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.Order;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.SkuInOrder;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.entity.SkuOrderInfo;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.OrderDetailsVO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.OrderListItemVO;
import cn.tt.tuantuanerp.tuantuanerp.comment.pojo.vo.UserDetailsVO;
import cn.tt.tuantuanerp.tuantuanerp.comment.security.LoginPrincipal;
import cn.tt.tuantuanerp.tuantuanerp.comment.web.JsonPage;
import cn.tt.tuantuanerp.tuantuanerp.comment.web.ServiceCode;
import cn.tt.tuantuanerp.tuantuanerp.orderservice.IOrderService;
import cn.tt.tuantuanerp.tuantuanerp.orderwebapi.mapper.OrderMapper;
import cn.tt.tuantuanerp.tuantuanerp.orderwebapi.mapper.SkuInOrderMapper;
import cn.tt.tuantuanerp.tuantuanerp.product.service.ISkuService;
import cn.tt.tuantuanerp.tuantuanerp.product.webapi.mapper.SkuMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 订单业务实现类
 * @author Wangyujie
 */
@Service
@Slf4j
@Transactional
@DubboService
public class OrderServiceImpl implements IOrderService {

    @Autowired
    SkuInOrderMapper skuInOrderMapper;
    @Autowired
    OrderMapper orderMapper;

    @DubboReference
    ISkuService skuService;
    @DubboReference
    IUserService userService;

    @Override
    public void addNew(OrderAddNewDTO orderAddNewDTO, LoginPrincipal loginPrincipal) {
        log.debug("开始处理添加订单的业务:{}",orderAddNewDTO);

        // 检查商品id列表内商品是否存在，依次存入商品信息
        List<SkuInOrderAddNewDTO> productList = orderAddNewDTO.getSkuIdList();
        // 遍历商品列表计算商品数量
        int countProduct = 0;
        BigDecimal cost = new BigDecimal("0.0");
        SkuOrderInfo[] skuOrderInfos = new SkuOrderInfo[productList.size()];
        for (int i = 0; i < productList.size(); i++) {
            SkuInOrderAddNewDTO sku = productList.get(i);
            log.debug("循环商品列表：{}",sku);
            // 累计商品总数量
            countProduct += sku.getSkuCount();
            // 取出sku信息
            SkuOrderInfo skuOrderInfo = new SkuOrderInfo();
            skuOrderInfo.setSkuId(sku.getSku());
            skuOrderInfo.setGoodsStock(sku.getSkuCount());
            skuOrderInfos[i] = skuOrderInfo;
        }
        log.debug("各项金额计算完成");

        // 调用SkuService方法确定成本
        skuOrderInfos = skuService.setOrderInfoBat(orderAddNewDTO.getOrderId(), skuOrderInfos, loginPrincipal);
        // 遍历信息数组,获取总成本
        for (SkuOrderInfo orderInfo : skuOrderInfos) {
            BigDecimal goodsCount = new BigDecimal(orderInfo.getGoodsStock());
            BigDecimal costPrice = orderInfo.getWareCostPrice();
            BigDecimal orderCost = goodsCount.multiply(costPrice).setScale(2,BigDecimal.ROUND_DOWN);
            cost = cost.add(orderCost);
        }

        // 添加订单到订单表
        Order order = new Order();

        // 根据orderAddNewDTO获取订单号
        order.setOrderId(orderAddNewDTO.getOrderId());
        BigDecimal productAmount = orderAddNewDTO.getOrderAmount();
        order.setProductAmount(productAmount);
        log.debug("商品总金额:{}",productAmount);
        order.setDiscount(new BigDecimal(0));
        // 因为暂无优惠,所以订单总金额同商品总金额一致
        BigDecimal orderAmount = productAmount;
        order.setOrderAmount(orderAmount);
        log.debug("订单总金额:{}",orderAmount);
        order.setCountProduct(countProduct);
        log.debug("商品总数:{}",countProduct);

        // 通过商品mapper计算商品总成本
        order.setCost(cost);
        log.debug("商品总成本:{}",cost);
        order.setState(0);
        String orderNotes = orderAddNewDTO.getOrderNotes();
        order.setOrderNotes(orderNotes!=null?orderNotes:"");

        // 商品付款时间应该后
        LocalDateTime now = LocalDateTime.now();
        order.setPayTime(now);
        order.setCreateTime(now);

        //获取当事人信息
        order.setCreatorId(loginPrincipal.getId());
        order.setOrderNotes(orderAddNewDTO.getOrderNotes());
        orderMapper.addNew(order);

        //完善订单商品表
        List<SkuInOrder> skuInOrderList = new ArrayList<>();
        for (SkuInOrderAddNewDTO skuInOrder : productList) {
            // 赋值并插入列表
            SkuInOrder inOrder = new SkuInOrder();
            log.debug("遍历的skuInOrder:{}",skuInOrder);
            BeanUtils.copyProperties(skuInOrder,inOrder);
            skuInOrderList.add(inOrder);
        }
        for (SkuInOrder skuInOrder : skuInOrderList) {
            for (SkuOrderInfo info : skuOrderInfos) {
                if (skuInOrder.getSku().equals(info.getSkuId())) {
                    skuInOrder.setWareCostPrice(info.getWareCostPrice());
                    break;
                }
            }
        }
        skuInOrderMapper.addNewBatch(skuInOrderList);

    }


    @Override
    public JsonPage<OrderListItemVO> listByCreatorId(LoginPrincipal loginPrincipal, Integer startIndex, Integer pageSize) {
        Long id = loginPrincipal.getId();
        log.debug("开始处理【查询订单】业务,用户id:{}",id);
        UserDetailsVO userDetailsVO = userService.getUserDetailsVOById(id);
        List<String> roles = userDetailsVO.getRoles();
        for (String role : roles) {
            if (role.contains("销售主管")||role.contains("管理员")){
                PageHelper.startPage(startIndex, pageSize);
                return JsonPage.restPage(new PageInfo<>(orderMapper.list()));
            }
        }
        PageHelper.startPage(startIndex, pageSize);
        return JsonPage.restPage(new PageInfo<>(orderMapper.listByCreatorId(id)));
    }

    @Override
    public OrderDetailsVO getDeatil(String id) {
        log.debug("开始处理【查询订单详情】业务,订单id:{}",id);
        return orderMapper.getDetailsByOrderId(id);
    }

    @Override
    public JsonPage<OrderListItemVO> getOrdersByOrderId(LoginPrincipal loginPrincipal, String id, Integer startIndex, Integer pageSize) {
        Long creatorId = loginPrincipal.getId();
        log.debug("开始处理【模糊查询订单号】业务,用户id:{}",id);
        UserDetailsVO userDetailsVO = userService.getUserDetailsVOById(creatorId);
        List<String> roles = userDetailsVO.getRoles();
        for (String role : roles) {
            if (role.contains("销售主管")||role.contains("超级管理员")||role.contains("系统管理员")){
                if (id != null ){
                    id = "%"+id+"%";
                }
                PageHelper.startPage(startIndex, pageSize);
                return JsonPage.restPage(new PageInfo<>(orderMapper.listByOrderId(id)));
            }
        }
        throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"用户权限不足，只有管理员和销售主管可以查询订单号！");
    }

    @Override
    public JsonPage<OrderListItemVO> listByCreator(LoginPrincipal loginPrincipal,Long id,Integer startIndex,Integer pageSize) {
        Long creatorId = loginPrincipal.getId();
        log.debug("开始处理【根据业务员ID查询订单】业务,业务员id:{}",id);
        UserDetailsVO userDetailsVO = userService.getUserDetailsVOById(creatorId);
        List<String> roles = userDetailsVO.getRoles();
        for (String role : roles) {
            if (role.contains("销售主管")||role.contains("超级管理员")||role.contains("系统管理员")){
                PageHelper.startPage(startIndex, pageSize);
                return JsonPage.restPage(new PageInfo<>(orderMapper.listByCreator(id)));
            }
        }
        PageHelper.startPage(startIndex, pageSize);
        return JsonPage.restPage(new PageInfo<>(orderMapper.listByCreator(creatorId)));
    }


}
